package cn.mcartoon.interceptor;


import cn.mcartoon.dto.ResultEnum;
import cn.mcartoon.utils.ResponseOutput;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 参数校验
 */
@Component
public class ValidateInterceptor extends HandlerInterceptorAdapter {

    Logger log = LoggerFactory.getLogger(ValidateInterceptor.class);


    //@Autowired
    //private ParamConfig paramConfig;
    /*@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        //获取URL
        String servletPath = request.getServletPath();
        //先判断空值
//        Map<String, String[]> reqParams = request.getParameterMap();
        Map<String, String> reqParams = new HashMap<>();
        Enumeration<String> names =  request.getParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String value = request.getParameter(name);
            reqParams.put(name, value);
        }
        Map<String, List<String>> notNullParams = notNullParems();
        for(String key :notNullParams.keySet()){
            // 如果这个接口有需要判断非空的参数
            if(servletPath.equals(key)){
                for (String notNullParam : notNullParams.get(key)) {
                    // 如果没有入参或者入参中不包括必传参数
                    if(reqParams == null || !reqParams.containsKey(notNullParam)
                            || reqParams.get(notNullParam) == null || StringUtils.isBlank(reqParams.get(notNullParam))){
                        log.info("接口：{}，的参数：【{}】不能为空", servletPath, notNullParam);
                        ResponseOutput.outputJson(response, ResultUtils.returnFail("参数【" + notNullParam + "】不能为空"));
                        return false;
                    }
                }
            }
        }
        return true;
    }*/

    /**
     * 前置处理方法
     * 在请求进入Handler之前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 维护需要非空验证的接口和参数，多个接口，每个接口可能会有多个参数需要进行验证
        Map<String, List<String>> map = notNullParems();
        // 获取当前请求路径
        String url = request.getServletPath();
        // 判断是否需要验证非空参数
        if(map.containsKey(url)){
            for(String param:map.get(url)){
                // 参数验证
                if (StringUtils.isBlank(request.getParameter(param))){
                    log.error("接口【" + url + "】的必传参数【" + param + "】，未传递！");
                    ResponseOutput.outputJson(response, ResultEnum.FAIL_PARAM);
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 初始化非空接口和参数
     * @return
     */
    public static Map<String, List<String>> notNullParems(){
        Map<String, List<String>> map = new HashMap<>();
        //  测试demo
        map.put("/api/demo/hello", Arrays.asList("name", "age"));
        // 漫画部分
        map.put("/api/cartoon/list", Arrays.asList("cartoonId"));
        map.put("/api/cartoon/collection", Arrays.asList("cartoonId","state"));
        map.put("/api/cartoon/state", Arrays.asList("cartoonId"));

        // 章节部分
        map.put("/api/chapter/list", Arrays.asList("cartoonId","chapterType"));
        map.put("/api/chapter/content/list", Arrays.asList("chapterId"));

        // 评论部分
        map.put("/api/comment/post", Arrays.asList("cartoonId","type"));
        map.put("/api/comment/list", Arrays.asList("cartoonId"));

        // 验证码
        map.put("/api/sms/verifyCode", Arrays.asList("phone","codeType"));

        // 用户部分
        map.put("/api/users/login/verification", Arrays.asList("phone","sign","imageCodes","password"));
        map.put("/api/users/register/verification", Arrays.asList("phone","sign","imageCodes","password","sms"));

        // 充值
        map.put("/api/recharge/submit", Arrays.asList("dicId"));

        // 购买章节
        map.put("/api/chapter/buy", Arrays.asList("chapterId"));
        return map;
    }

}
